package deploy

import (
	"fmt"
	"os"
	"regexp"
	"strings"

	"gddgame.cc/galaxy/utils"
	"gddgame.cc/galaxy/utils/def"
	"github.com/toolkits/file"
)

type Wrap struct {
	path    string
	env     []string
	context def.Context
	record  *ProjectRecord

	result  string
	process Process
}

func (wrap *Wrap) Context() def.Context {
	return wrap.context
}

func (wrap *Wrap) WorkDir() string {
	return wrap.path
}

func (wrap *Wrap) Env() []string {
	if wrap.env != nil && len(wrap.env) > 0 {
		return wrap.env
	}
	// 首字母大写的写入环境
	for key, value := range wrap.record.Vars {
		if len(key) == 0 {
			continue
		}
		if 'A' <= key[0] && key[0] <= 'Z' {
			wrap.env = append(wrap.env, key+"="+value)
		}
	}
	fmt.Println("Env:", wrap.env)
	return wrap.env
}

func (wrap *Wrap) Nodes() []string {
	return wrap.record.Nodes
}

func (wrap *Wrap) Process(process Process, result string, finish bool) {
	if result == "" && !finish {
		return
	}
	wrap.result += result
	wrap.process = process
	_ = updateRecord(wrap.record, process, wrap.record.Result+wrap.result, false)
	if finish {
		wrap.record.Result += wrap.result
		wrap.result = ""
	}
}
func (wrap *Wrap) Error(err error, finish bool) {
	wrap.record.Result += "Error:" + err.Error() + "\n"
	if finish {
		_ = updateRecord(wrap.record, Fail, wrap.record.Result, finish)
	} else {
		_ = updateRecord(wrap.record, wrap.process, wrap.record.Result, finish)
	}
}
func (wrap *Wrap) Var(key string) string {
	return wrap.record.Vars[key]
}

func (wrap *Wrap) Replace(source string) string {
	result := varReg.FindAllStringSubmatch(source, -1)
	for _, match := range result {
		source = strings.Replace(source, match[0], wrap.Var(match[1]), 1)
	}
	return source
}

func (wrap *Wrap) Finish() {
	_ = updateRecord(wrap.record, Success, wrap.record.Result, true)
}

func (wrap *Wrap) GenerateConfig(path string) {
	var err error
	realPath := wrap.Var(ProjectPath) + path
	result := ""
	for _, config := range wrap.record.Configs {
		if !config.Status {
			result += "Config miss:" + config.Name + "\n"
			continue
		}
		realFile := realPath + "/" + config.Name
		targetFile := realPath + "/" + wrap.Replace(config.Target)
		if config.Target == "" {
			targetFile = realFile
		}
		if file.IsExist(realFile) {
			result += "Config exist:" + config.Name + "\n"
			config.Content, err = file.ToString(realFile)
			if err != nil {
				continue
			}
		}
		if file.IsExist(targetFile) {
			if err != os.Remove(targetFile) {
				continue
			}
		}
		config.Content = wrap.Replace(config.Content)
		if f, err := os.OpenFile(targetFile, os.O_WRONLY|os.O_CREATE, 0755); err != nil {
			result += "Config error:" + config.Name + "->" + err.Error() + "\n"
			continue
		} else {
			if _, err := f.Write(utils.ToBytes(config.Content)); err != nil {
				result += "Config error:" + config.Name + "->" + err.Error() + "\n"
				continue
			}
			_ = f.Close()
		}

		result += "Config generate:" + config.Name + "\n"
	}
	wrap.record.Result += wrap.result + result
	_ = updateRecord(wrap.record, wrap.process, wrap.record.Result, false)
}

var varReg = regexp.MustCompile(`{{([^}]+)}}`)
